package cn.mw.cmdb.service.impl;

import cn.mw.cmdb.entity.AssetsDiscoverInfo;
import cn.mw.cmdb.entity.InstanceInfo;
import cn.mw.cmdb.service.AssetsManageService;
import cn.mw.cmdb.service.FunctionalModuleService;
import cn.mw.components.mongodb.exception.BusinessException;
import cn.mw.microMonitorCommon.util.SpringUtils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

public class MonitorModuleServiceImpl implements FunctionalModuleService<InstanceInfo> {

    private AssetsManageService assetsManageService = null;

    @Override
    public Boolean action(InstanceInfo context) throws Exception {
        // 运维监控
        if (null == assetsManageService) {
            this.assetsManageService = SpringUtils.getBean(AssetsManageService.class);
        }
        this.assetsManageService.addMonitor(context);

        return true;
    }

    @Override
    public <R> Boolean batchAction(R context) throws Exception {
        if (null == assetsManageService) {
            this.assetsManageService = SpringUtils.getBean(AssetsManageService.class);
        }
        Class<?> convert = convert(context);
        Object o = convert.getDeclaredConstructor().newInstance();
        return true;
    }


    @Override
    public <R> Boolean batchHandle(List<InstanceInfo> context) throws Exception {
        if (null == assetsManageService) {
            this.assetsManageService = SpringUtils.getBean(AssetsManageService.class);
        }
        this.assetsManageService.batchAddMonitor(context);
        return true;
    }

    protected Class<?> convert(Object obj) {
        Type[] genericInterfaces = obj.getClass().getGenericInterfaces();
        for (Type genericInterface : genericInterfaces) {
            if (genericInterface instanceof ParameterizedType dto) {
                Type[] actualTypeArguments = dto.getActualTypeArguments();
                if (actualTypeArguments.length > 0) {
                    return (Class<?>) actualTypeArguments[0];
                }
            }
        }
        throw new BusinessException("conversion-object-not-found");
    }

}
